package com.sduept.nwld.dataserver.controller.ledger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.primefaces.model.StreamedContent;
import org.springframework.beans.factory.annotation.Autowired;

import com.sduept.bigdata.document.core.CommonDocumentProperties;
import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.ledger.manager.SubstationLedgerManager;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.model.SubstationLedger;
import com.sduept.cim.model.core.Substation;
import com.sduept.bigdata.weather.map.MapDataCache;

@Named
@ViewScoped
public class SubstationLedgerController extends AbstractController {

    private static final long serialVersionUID = -2918314107112100079L;
    @Autowired
    private CommonDocumentProperties pros;
    @Autowired
    private SubstationLedgerManager stationLedgerM;
    @Autowired
    private MapDataCache cc;

    private LazyDataModel<SubstationLedger> model;
    private long rowCount = 0;
    private List<SubstationLedger> stationLedgerList = new ArrayList<SubstationLedger>();
    private List<SubstationLedger> selectedStationledgerList = new ArrayList<SubstationLedger>();
    /**
     * 查询条件
     */
    private String selectdStandVolLevel = "500"; //电压等级默认为500
    private String equipmentName = ""; // 设备名称
    private SubstationLedger queryLedger = new SubstationLedger();
    private SubstationLedger editLedger = new SubstationLedger();

    private StreamedContent templateFile;

    @PostConstruct
    public void init() {
        initSubstationLedgerTable();
    }

    private void initQueryLedger() {
        queryLedger.setAssetOwner("全部");
        queryLedger.setDispatchUnit("全部");
        queryLedger.setDispatchUnitId(null);
        queryLedger.setMaintenanceUnit("全部");
        queryLedger.setMaintenanceUnitId(null);
        queryLedger.setPrimaryEquipmentScope("全部");
        queryLedger.setSecondaryEquipmentScope("全部");
    }

    public void initDate() {
        List<SubstationLedger> ledgerList = stationLedgerM.findAllSubstationLedger();
        if (ledgerList.size() == 0) {
            try {
                stationLedgerM.initAllSubstation();
            } catch (SQLException e) {
                addErrorMessage("初始化数据失败");
                e.printStackTrace();
            }
            initSubstationLedgerTable();
        } else {
            alertErrorMessage("已有数据，不允许重新初始化！");
        }
    }

    /**
     * 当查询参数为空时，与查询参数取值为“未设置”相同
     * 当仅有部分查询参数有值时，未设置值的参数应该默认查询全部
     * 注：当变电站名称不为空时，默认其他选择的参数无效，即进按照变电站名称进行查询
     */
    private void resetParamBeforeQuery() {
        // 如果变电站名称不为空，则查找条件仅变电站名称有效，即仅按照变电站名称进行查询
        if (StringUtils.isNotEmpty(equipmentName)) {
            initQueryLedger();
        } else {
            // 变电站名称为空时
            int i = 0;
            if (StringUtils.isNotEmpty(queryLedger.getDispatchUnit())) {
                i++;
            }
            if (StringUtils.isNotEmpty(queryLedger.getMaintenanceUnit())) {
                i++;
            }
            if (StringUtils.isNotEmpty(queryLedger.getAssetOwner())) {
                i++;
            }
            if (StringUtils.isNotEmpty(queryLedger.getPrimaryEquipmentScope())) {
                i++;
            }
            if (StringUtils.isNotEmpty(queryLedger.getSecondaryEquipmentScope())) {
                i++;
            }
            if (i > 0 && i < 5) {
                // 有空的查询参数，有有值的查询参数，此时，需要将空参数全部变为全部
                if (StringUtils.isEmpty(queryLedger.getDispatchUnit())) {
                    queryLedger.setDispatchUnit("全部");
                }
                if (StringUtils.isEmpty(queryLedger.getMaintenanceUnit())) {
                    queryLedger.setMaintenanceUnit("全部");
                }
                if (StringUtils.isEmpty(queryLedger.getAssetOwner())) {
                    queryLedger.setAssetOwner("全部");
                }
                if (StringUtils.isEmpty(queryLedger.getPrimaryEquipmentScope())) {
                    queryLedger.setPrimaryEquipmentScope("全部");
                }
                if (StringUtils.isEmpty(queryLedger.getSecondaryEquipmentScope())) {
                    queryLedger.setSecondaryEquipmentScope("全部");
                }
            }
        }
    }

    public void initSubstationLedgerTable() {
        model = new LazyDataModel<SubstationLedger>() {
            private static final long serialVersionUID = 2555889870899232640L;

            @Override
            public List<SubstationLedger> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
                resetParamBeforeQuery();
                stationLedgerList = stationLedgerM.queryStationLedgerByCondition(selectdStandVolLevel, equipmentName, queryLedger.getDispatchUnit(), null, queryLedger.getMaintenanceUnit(), null, queryLedger.getAssetOwner(), queryLedger.getPrimaryEquipmentScope(), queryLedger.getSecondaryEquipmentScope(), new int[]{first, first + pageSize});
                return stationLedgerList;
            }

            @Override
            public SubstationLedger getRowData(String rowKey) {
                for (SubstationLedger t : stationLedgerList) {
                    if (t.getId().equals(rowKey)) {
                        return t;
                    }
                }
                return null;
            }

            @Override
            public Object getRowKey(SubstationLedger object) {
                for (SubstationLedger t : stationLedgerList) {
                    if (t.getId().equals(object.getId())) {
                        return t;
                    }
                }
                return null;
            }
        };
        resetParamBeforeQuery();
        rowCount = stationLedgerM.countSubstationLedger(selectdStandVolLevel, equipmentName, queryLedger.getDispatchUnit(), null, queryLedger.getMaintenanceUnit(), null, queryLedger.getAssetOwner(), queryLedger.getPrimaryEquipmentScope(), queryLedger.getSecondaryEquipmentScope());
        model.setRowCount((int) rowCount);
    }

    public void resetQueryCondition() {
        queryLedger = new SubstationLedger();
        equipmentName = null;
        selectdStandVolLevel = "500";
        initSubstationLedgerTable();
    }

    /**
     * 编辑时，如果选中多条记录，调度单位、运维单位等信息显示为空，
     * 如果选中一条记录，则显示当前记录的调度单位、运维单位等信息
     * 默认资产归属为南网
     */
    public void preEdit() {
        if (selectedStationledgerList.size() == 1) {
            editLedger = selectedStationledgerList.get(0);
            if (StringUtils.isEmpty(editLedger.getAssetOwner())) {
                editLedger.setAssetOwner("南网");
            }
        } else {
            editLedger.setAssetOwner("南网");
        }
    }

    public void save() {
        for (SubstationLedger ledger : selectedStationledgerList) {
            ledger.setAssetOwner(editLedger.getAssetOwner());
            ledger.setDispatchUnit(editLedger.getDispatchUnit());
            ledger.setDispatchUnitId(editLedger.getDispatchUnitId());
            ledger.setMaintenanceUnit(editLedger.getMaintenanceUnit());
            ledger.setMaintenanceUnitId(editLedger.getMaintenanceUnitId());
            ledger.setUnitType(editLedger.getUnitType());
            ledger.setPrimaryEquipmentScope(editLedger.getPrimaryEquipmentScope());
            ledger.setPrimaryEquipmentScopeRemark(editLedger.getPrimaryEquipmentScopeRemark());
            ledger.setSecondaryEquipmentScope(editLedger.getSecondaryEquipmentScope());
            ledger.setSecondaryEquipmentScopeRemark(editLedger.getSecondaryEquipmentScopeRemark());
        }
        try {
            stationLedgerM.saveSubstationLedgers(selectedStationledgerList);
            addSuccessMessage("保存成功！");
        } catch (SQLException e) {
            addErrorMessage("保存失败");
        }
        selectedStationledgerList.clear();
    }

    /**
     * 清空选中变电站的所有单位设置（调管单位、运维单位、资产归属、一|二次设备检查范围等）
     */
    public void cleanLedgers() {
        if (selectedStationledgerList.size() > 0) {
            for (SubstationLedger entity : selectedStationledgerList) {
                entity.setAssetOwner(null);
                entity.setDispatchUnit(null);
                entity.setDispatchUnitId(null);
                entity.setMaintenanceUnit(null);
                entity.setMaintenanceUnitId(null);
                entity.setPrimaryEquipmentScope(null);
                entity.setPrimaryEquipmentScopeRemark(null);
                entity.setSecondaryEquipmentScope(null);
                entity.setSecondaryEquipmentScopeRemark(null);
                entity.setUnitType(null);
            }
            try {
                stationLedgerM.saveSubstationLedgers(selectedStationledgerList);
                addSuccessMessage("清除成功！");
            } catch (SQLException e) {
                e.printStackTrace();
                addErrorMessage("清除失败");
            }
            selectedStationledgerList.clear();
        }
        initSubstationLedgerTable();
    }

    /**
     * 模板下载
     */
    public void fileDownloadView() {
        InputStream stream = null;
        try {
            stream = new FileInputStream(new File(pros.getTempletePath() + "equipmentLedger.xlsx"));
            templateFile = new DefaultStreamedContent(stream, "xlsx", "equipmentLedger.xlsx");
        } catch (FileNotFoundException e) {
            addErrorMessage("下载文件失败，请联系技术人员！");
            e.printStackTrace();
        }
    }

    public void openUploadDialog() {
        Map<String, Object> options = new HashMap<String, Object>();
        options.put("resizable", true);
        options.put("draggable", true);
        options.put("modal", true);
        options.put("width", 600);
        options.put("height", 200);
        Map<String, List<String>> params = new HashMap<>();
        List<String> param = new ArrayList<>();
        param.add("1");    //设置去除前几行
        params.put("ingnoreRows", param);
        openDialog("/ui/common/upload_excel_define", params, options);
    }

    /**
     * 文件上传
     *
     * @param event
     */
    // 0变电站id  1变电站名称     2调度单位     3运维单位     4单位类型     5资产归属      6一次设备检修范围   7一次设备检修范围备注	8二次设备检修范围	9二次设备检修范围备注
    @SuppressWarnings("unchecked")
    public void onSelectorChosen(SelectEvent event) {
        List<List<String>> objs = (List<List<String>>) event.getObject();
        List<Integer> errorList = new ArrayList<Integer>();
        List<SubstationLedger> ledgerList = new ArrayList<SubstationLedger>();
        Map<String, Substation> stationMap = cc.getStationid_map();
        Map<String, SubstationLedger> ledgerMap = getAllSubstationLedgerMap();
        try {
            int rowIndex = 0;
            for (List<String> list : objs) {
                // 当上传数据不完整时，用空值填充list
                if (list.size() < 10) {
                    for (int i = list.size(); i < 11; i++) {
                        list.add("");
                    }
                }
                rowIndex++;
                // 上传时，首先判断变电站id是否存在
                Substation station = stationMap.get(list.get(0));
                if (null != station) {
                    //该变电站存在，可以存入数据库中
                    SubstationLedger ledger = ledgerMap.get(list.get(0));
                    if (null == ledger) {
                        ledger = new SubstationLedger();
                    }
                    ledger.setCimId(list.get(0));
                    ledger.setEquipmentType("变电站");
                    ledger.setName(list.get(1));
                    ledger.setDispatchUnit(list.get(2));
                    // TODO 设置单位id
                    ledger.setUnitType(list.get(4));
                    ledger.setAssetOwner(list.get(5));
                    ledger.setPrimaryEquipmentScopeRemark(list.get(7));
                    ledger.setSecondaryEquipmentScopeRemark(list.get(9));
                    // 3运维单位、6一次设备检修范围、8二次设备检修范围三个的数值是一样的
                    String sameValue = "";
                    if (StringUtils.isNotEmpty(list.get(8))) {
                        sameValue = list.get(8);
                    }
                    if (StringUtils.isNotEmpty(list.get(6))) {
                        sameValue = list.get(6);
                    }
                    if (StringUtils.isNotEmpty(list.get(3))) {
                        sameValue = list.get(3);
                    }
                    ledger.setMaintenanceUnit(StringUtils.isNotEmpty(list.get(3)) ? list.get(3) : sameValue);
                    // TODO 设置单位id
                    ledger.setPrimaryEquipmentScope(StringUtils.isNotEmpty(list.get(6)) ? list.get(6) : sameValue);
                    ledger.setSecondaryEquipmentScope(StringUtils.isNotEmpty(list.get(8)) ? list.get(8) : sameValue);
                    ledgerList.add(ledger);
                } else {
                    //该变电站不存在，将其行数加入错误列表中
                    errorList.add(rowIndex);
                }
            }
            if (ledgerList.size() > 0) {
                for (SubstationLedger substationLedger : ledgerList) {
                    stationLedgerM.createOrUpdateSubstationLedger(substationLedger);
                }
                addSuccessMessage("文件上传成功！");
            }
            StringBuffer sb = new StringBuffer();
            if (errorList.size() != 0) {
                sb.append("上传的文件中，第：");
                for (Integer i : errorList) {
                    sb.append(i + "、");
                }
                sb.append("行变电站Id不存在，请核实后再次上传！");
                alertErrorMessage(sb + "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            addErrorMessage("表格数字有误，请仔细核对！");
            return;
        }
        initSubstationLedgerTable();
    }

    private Map<String, SubstationLedger> getAllSubstationLedgerMap() {
        Map<String, SubstationLedger> ledgerMap = new HashMap<String, SubstationLedger>();
        List<SubstationLedger> allLedgers = stationLedgerM.findAllSubstationLedger();
        for (SubstationLedger ledger : allLedgers) {
            ledgerMap.put(ledger.getCimId(), ledger);
        }
        return ledgerMap;
    }

    /**
     * 选择部门后，设置SubstationLedger的对应值
     *
     * @param event
     */
    public void onDesorgDepartChosen(SelectEvent event) {
        ManagementUnitDict dept = (ManagementUnitDict) event.getObject();
        editLedger.setDispatchUnit(dept.getName());
        editLedger.setDispatchUnitId(dept.getId());
    }

    /**
     * 选择运维部门后，设置SubstationLedger的对应值
     *
     * @param event
     */
    public void onOpDepartChosen(SelectEvent event) {
        ManagementUnitDict dept = (ManagementUnitDict) event.getObject();
        editLedger.setMaintenanceUnit(dept.getName());
        editLedger.setMaintenanceUnitId(dept.getId());
        if (dept.getName().contains("超高压")) {
            editLedger.setUnitType("超高压分局");
        } else if (dept.getName().contains("供电局")) {
            editLedger.setUnitType("供电局");
        } else if (dept.getName().contains("电厂")) {
            editLedger.setUnitType("发电厂");
        } else {
            editLedger.setUnitType(null);
        }
    }

    /**
     * 选择一次设备检修范围
     *
     * @param event
     */
    public void onPrimaryScopeChosen(SelectEvent event) {
        ManagementUnitDict dept = (ManagementUnitDict) event.getObject();
        editLedger.setPrimaryEquipmentScope(dept.getName());
    }

    /**
     * 选择二次设备检修范围
     *
     * @param event
     */
    public void onSecondryScopeChosen(SelectEvent event) {
        ManagementUnitDict dept = (ManagementUnitDict) event.getObject();
        editLedger.setSecondaryEquipmentScope(dept.getName());
    }

    public LazyDataModel<SubstationLedger> getModel() {
        return model;
    }

    public void setModel(LazyDataModel<SubstationLedger> model) {
        this.model = model;
    }

    public long getRowCount() {
        return rowCount;
    }

    public void setRowCount(long rowCount) {
        this.rowCount = rowCount;
    }

    public List<SubstationLedger> getSelectedStationledgerList() {
        return selectedStationledgerList;
    }

    public void setSelectedStationledgerList(List<SubstationLedger> selectedStationledgerList) {
        this.selectedStationledgerList = selectedStationledgerList;
    }

    public String getEquipmentName() {
        return equipmentName;
    }

    public void setEquipmentName(String equipmentName) {
        this.equipmentName = equipmentName;
    }

    public SubstationLedger getQueryLedger() {
        return queryLedger;
    }

    public void setQueryLedger(SubstationLedger queryLedger) {
        this.queryLedger = queryLedger;
    }

    public SubstationLedger getEditLedger() {
        return editLedger;
    }

    public void setEditLedger(SubstationLedger editLedger) {
        this.editLedger = editLedger;
    }

    public StreamedContent getTemplateFile() {
        return templateFile;
    }

    public void setTemplateFile(StreamedContent templateFile) {
        this.templateFile = templateFile;
    }

    public String getSelectdStandVolLevel() {
        return selectdStandVolLevel;
    }

    public void setSelectdStandVolLevel(String selectdStandVolLevel) {
        this.selectdStandVolLevel = selectdStandVolLevel;
    }

}
